package tech.heptagram.staff.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.heptagram.staff.domain.Sequence;
import tech.heptagram.staff.domain.SequenceType;
import tech.heptagram.staff.mapper.SequenceMapper;
import tech.heptagram.staff.service.SequenceService;

import javax.annotation.Resource;

/**
 * 序列号生产器
 *
 * @Desc 用户系统中编号需要保证唯一，并且呈递增序列的单号 Created by wangkun23 on 2017/9/7.
 */
@Service
public class SequenceServiceImpl implements SequenceService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SequenceMapper sequenceMapper;


    /**
     * 生成员工工号
     *
     * @return
     */
    @Override
    public synchronized String generateStaffJobNo() {
        return String.valueOf(getNextId(SequenceType.STAFF_JOB_NUM));
    }


    /**
     * 读取下一个ID
     *
     * @return
     */
    @Transactional
    Integer getNextId(SequenceType sequenceType) {
        Sequence sequence = new Sequence(sequenceType.toString(), -1);
        Sequence result = sequenceMapper.getSequence(sequence);
        if (result == null) {
            logger.warn("A null sequence was returned from the database {}", sequence);
            //throw new RuntimeException("Error: A null sequence was returned from the database " + sequence);
            Sequence entity = new Sequence(sequenceType.toString(), 0);
            sequenceMapper.insert(entity);
            //重新调用一次
            result = sequenceMapper.getSequence(sequence);
        }
        Sequence parameterObject = new Sequence(sequenceType.toString(), result.getNextId() + 1);
        sequenceMapper.updateSequence(parameterObject);
        return result.getNextId();
    }


}
